#!/usr/bin/env python
# coding: utf-8

import freeswitch
from cloudcallRedis import rdc
import time
import random

# <extension name="python test script2">
#         <condition field="destination_number" expression="^083(10\d{2})$">
#             <action application="python" data="outboundcall ${1}"/>
#         </condition>
# </extension>

# rdc.get_state()
# rdc.get_cop_num('20358')
# rdc.get_last_call_info('LastCallInfo:02023398853:13724059427')

def handler(session, args):  # args is string
    freeswitch.console_log("info", "test call args string is:" + args)
    session.setAutoHangup(False)
    uuid = session.getVariable("uuid")
    X_uuid = session.getVariable("sip_h_X-uuid")
    X_create_user_id = session.getVariable("sip_h_X-create_user_id")
    X_city = session.getVariable("sip_h_X-city")
    if X_uuid is None:
        X_uuid = "null"
    if X_create_user_id is None:
        X_create_user_id = "null"
    if X_city is None:
        X_city = "null"
    freeswitch.consoleLog("NOTICE","call " + uuid + " extend params: X_uuid:" + X_uuid +
                          ", X_create_user_id:" + X_create_user_id + " X_city:" + X_city + "\n")
    if X_create_user_id != 'null' and X_city != 'null':
        session.setVariable("continue_on_fail", "false")
        session.setVariable("hangup_after_bridge", "true")
        session.setVariable("jitterbuffer_msec", "260:400:20")
        session.execute("export", "session_id=${uuid}")
        session.execute("export", "call_timeout=60")
        # TODO
        session.setHangupHook("myHangupHook", "test myHangupHook")
        # save record file
        today = time.strftime("%Y%m%d", time.localtime())

        record_save_base_paths = ["/cloudcall_file/rec_20050/freeswitchRecordFile/",
                                  "/cloudcall_file/rec_20051/freeswitchRecordFile/"]
        path = random.choice(record_save_base_paths) + today + "/" + uuid + ".wav"
        freeswitch.console_log("info", "choice path: " + path)
        session.execute("export", "nolocal:execute_on_answer=record_session " + path)
        # dict(b'',b'')
        # show_num = rdc.get_cop_num(X_create_user_id,X_city)
        show_num = "1002"
        call_str = "user/%s" % (args)
        freeswitch.console_log("info", "bridge string is:" + call_str)
        session.execute("bridge", call_str)
        session.hangup()
    else:
        session.hangup("UNALLOCATED_NUMBER")


def myHangupHook(session, status, args):
    freeswitch.consoleLog("NOTICE", "myHangupHook: " + status + "\n")